﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Configuration; 
namespace ZhiHeng.OneCard.WpfClient.Common
{
    public static class CheckServer
    {
       /// <summary>
       /// 检查能否与服务器连接
       /// </summary>
       /// <param name="Handler">发送内容</param>
       /// <param name="ip">服务器IP</param>
       /// <param name="port">端口</param>
       /// <returns></returns>
        public static bool Check(string Handler)
        {
            Socket Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
            try
            {
                string ip = ConfigurationManager.AppSettings["ServerIP"].ToString();
                int port = Convert.ToInt32(ConfigurationManager.AppSettings["port"].ToString());
                IPAddress ipAddress = IPAddress.Parse(ip);
                IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port);
                Sock.SendTimeout = 1;
                Sock.Connect(remoteEndPoint);
                byte[] bytSend = Encoding.UTF8.GetBytes(Handler);
                Sock.Send(bytSend);
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = Sock.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
                if (recvStr == "Ok")
                    return true;
                else
                    return false;
                
            }
            catch (Exception ex)
            {
                return false;
            }
            finally { Sock.Dispose(); Sock.Close(); }
        }
    }
}
